package org.monster.boot;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * dos命令接收器<br>
 * 和{@link DosSender}类通信的线程类
 *
 * @author Monster
 */
public class DosReceiver extends Thread {

    /**
     * 日志器
     */
    private static final Logger logger = Logger.getLogger(DosReceiver.class.getName());
    /**
     * 负责暂存输入字符的{@link StringBuilder}类的字段
     */
    private static final StringBuilder buffer = new StringBuilder();
    /**
     * 管道输入流
     * 和{@link DosSender}线程通信通道流字段
     */
    private PipedInputStream pipedIn;
    /**
     * 容器
     * {@link Container} dos容器接口
     */
    private Container container;

    /**
     * 带参的构造方法({@link DosContainer})
     *
     * @param container 容器
     */
    public DosReceiver(Container container) {
        this.pipedIn = new PipedInputStream();
        this.container = container;
    }

    /**
     * 获取输入流
     * 获取与{@link DosSender}的输出流
     *
     * @return {@link PipedInputStream}
     */
    public PipedInputStream getPipedIn() {
        return pipedIn;
    }

    /**
     * 运行
     */
    @Override
    public void run() {
        BufferedInputStream bufferedIn = new BufferedInputStream(pipedIn);
        int len;
        char ch;
        try {
            while (true) {
                len = bufferedIn.read();
                ch = (char) len;
                if (ch == '}') {
                    buffer.append(ch);
                    String str = buffer.toString();
                    if (str.contains("cls")) {
                        clear();
                        return;
                    }
                    int start = str.indexOf('{');
                    if (start != -1) {
                        str = str.substring(start, str.length());
                    }
                    container.put(str);
                    clear();
                } else {
                    buffer.append(ch);
                }

            }
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 清除
     * 清除暂存的{@link StringBuilder}类的字符
     */
    public void clear() {
        buffer.delete(0, buffer.length());
    }
}
